﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Barebones.Components;
using Barebones.Dependencies;

namespace Meat.Resources
{
    public class ContentResource<T> : IResource where T : class
    {
        ResourceLoader m_Loader;
        T m_Resource;
        String m_ResourceName;

        public String Name
        { get { return m_ResourceName; } }

        public ContentResource(String resourceName)
        {
            m_ResourceName = resourceName;
        }

        public void SetLoader(ResourceLoader loader)
        {
            m_Loader = loader;
        }

        public GetT Get<GetT>() where GetT : class
        {
            if (!typeof(GetT).IsAssignableFrom(typeof(T)))
                throw new InvalidOperationException("Tried to get a resource of type " + typeof(T).Name + " instead of actual type " + typeof(GetT).Name);

            if (m_Resource == null)
                ForceLoad();

            return m_Resource as GetT;
        }

        public void Reset()
        {
            m_Resource = null;
        }

        public void ForceLoad()
        {
            if (m_Loader == null)
                throw new InvalidOperationException("Resource<" + typeof(T).Name + "> Loader dependency not resolved yet");

            if (m_Loader.Content == null)
                throw new InvalidOperationException("Resource<" + typeof(T).Name + "> Tried to retrieve resource before Content has been initialized");

            m_Resource = m_Loader.Content.Load<T>(m_ResourceName);
        }

        public AbstractHandle ToHandle()
        {
            return new Handle<T>(m_ResourceName);
        }
    }
}
